package com.itrip.auth.controller;

import com.itrip.auth.service.MailService;
import com.itrip.auth.service.RegService;
import com.itrip.auth.service.SmsService;
import com.itrip.beans.domain.ItripUser;
import com.itrip.beans.dto.Dto;
import com.itrip.utils.DtoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class RegController {

    @Autowired
    private RegService regService;

    @PostMapping("/registerbyphone")
    public Dto registerbyphone(@RequestBody ItripUser itripUser) {
        try {
            if (regService.registerbyphone(itripUser) > 0) {
                return DtoUtil.returnSuccess("注册成功!");
            }else{
                return DtoUtil.returnSuccess("注册失败!");
            }
        }catch(RuntimeException re){
            return DtoUtil.returnFail(re.getMessage(),"10001");
        }catch (Exception e) {
            return DtoUtil.returnFail(e.getMessage(),"10002");
        }
    }

    @PutMapping("/validatephone")
    public Dto validatephone(String user,String code){
        try {
            if(regService.validatephone(user,code)){
                return DtoUtil.returnSuccess("激活成功!");
            }else{
                return DtoUtil.returnFail("激活失败!","20001");
            }
        } catch (Exception e) {
            return DtoUtil.returnFail(e.getMessage(),"20003");
        }
    }

    @GetMapping("/ckusr")
    public Dto ckusr(String name){
        if(regService.ckusr(name)){
            return DtoUtil.returnSuccess();
        }
        return DtoUtil.returnFail("账户已存在,请重新输入","30012");
    }

    @PostMapping("/doregister")
    public Dto doregister(@RequestBody ItripUser itripUser) {
        try {
            if (regService.doregister(itripUser) > 0) {
                return DtoUtil.returnSuccess("注册成功!");
            }else{
                return DtoUtil.returnSuccess("注册失败!");
            }
        }catch(RuntimeException re){
            return DtoUtil.returnFail(re.getMessage(),"10001");
        }catch (Exception e) {
            return DtoUtil.returnFail(e.getMessage(),"10002");
        }
    }

    @PutMapping("/activate")
    public Dto activate(String user,String code){
        try {
            if(regService.activate(user,code)){
                return DtoUtil.returnSuccess("激活成功!");
            }else{
                return DtoUtil.returnFail("激活失败!","20001");
            }
        } catch (Exception e) {
            return DtoUtil.returnFail(e.getMessage(),"20003");
        }
    }
}
